<template>
  <div class="home">
    <div class="banner">
      <img src="@/assets/images/banner.png" />
    </div>
    <!-- <div @click="wxlogin">登录</div> -->
    <div class="content">
      <div class="title">
        <img class="icon_fire" src="@/assets/images/fire.png" />
        <span class="txt">热门红包</span>
      </div>
      <div class="list">
        <div
          class="item"
          v-for="(item, index) in dataList"
          :key="index"
          @click="goDetail(item)"
        >
          <!-- <img class="item_img" :style="{ backgroundImage: item.img }" /> -->
          <div
            class="item_img"
            :style="`background-image:url(${item.imageList})`"
          ></div>
          <div class="item_content">
            <div class="item_tt">
              {{ item.name }}
            </div>
            <div class="item_price">
              ¥<span class="item_price_txt">{{ item.price }}</span>
            </div>
            <div class="item_footer">
              <div class="item_num">
                销量<span class="item_num_txt">{{ item.saleNum }}</span>
              </div>
              <div class="item_btn" @click.stop="handleBuy(item.bagId)">
                立即购买
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <div class="footerbox">
        <div
          class="menu_item"
          :class="menuIndex == index ? 'active' : ''"
          v-for="(item, index) in menuList"
          :key="index"
          @click="goRouter(item, index)"
        >
          <img
            class="menu_icon"
            :src="menuIndex == index ? item.img2 : item.img"
          />
          <div class="menu_name">{{ item.name }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import commonApi from "@/api/commonApi";
import { getCookies, getQueryString } from "@/utils/util.js";
import axios from "axios";
const base_url = process.env.BASE_API;
import { Toast } from "vant";
import nav1 from "@/assets/images/nav1.png";
import nav1_check from "@/assets/images/nav1_check.png";
import nav2 from "@/assets/images/nav2.png";
import nav2_check from "@/assets/images/nav2_check.png";
import main from "@/assets/images/main.jpg";
export default {
  components: {
    Toast,
  },
  data() {
    return {
      dataList: [],

      userId: getCookies("userId"),
      menuList: [
        { img: nav1, img2: nav1_check, name: "商城", url: "" },
        { img: nav2, img2: nav2_check, name: "订单", url: "/order" },
      ],
      menuIndex: 0,
    };
  },

  mounted() {
    this.getRedList();
    // this.ocrCarNo()
    console.log(base_url);

    if (getQueryString("uta")) {
      localStorage.setItem("uta", getQueryString("uta"));
    }
    if (getQueryString("code")) {
      commonApi.wxh5Login({ wxcode: getQueryString("code") }).then((res) => {
        localStorage.setItem("userId", res.userId);
        localStorage.setItem("openid", res.openid);
      });
    } else {
      if (!getCookies("userId")) {
        this.wxlogin();
      }
    }
  },

  methods: {
    wxlogin() {
      const appId = "wx48a1842aee97884c"; // 替换为你的微信公众号的 AppID
      const redirectUri = `${encodeURIComponent(window.location.href)}`; // 授权后重定向的回调链接地址，需要进行 URL 编码
      console.log(redirectUri);
      const scope = "snsapi_base"; // 或 'snsapi_base /snsapi_userinfo'，根据需求选择
      const wechatAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
      console.log(wechatAuthUrl);
      window.location.href = wechatAuthUrl;
    },
    getRedList() {
      commonApi.getRedList({}).then((res) => {
        console.log(res);
        if (res && res.length != 0) {
          this.dataList = res;
        }
      });
    },

    goDetail(item) {
      // localStorage.setItem("bagId", item.bagId);
      this.$router.push({
        path: "/detail",
        query: { bagId: item.bagId },
      });
    },

    handleBuy(bagId) {
      let vm = this;
      if (getCookies("userId")) {
        commonApi
          .orderApply({
            bagId: bagId,
            uta: getCookies("uta") || "",
            openid: getCookies("openid") || "",
            userId: getCookies("userId") || "",
          })
          .then((res) => {
            if (res.code != 500) {
              commonApi
                .getPayInfo({
                  openid: getCookies("openid") || "",
                  userId: getCookies("userId") || "",
                  orderId: res.orderId,
                })
                .then((el) => {
                  let payInfo = JSON.parse(el.payInfo);
                  let data = payInfo.wechatData;
                  wx.config({
                    debug: false, // 这里一般在测试阶段先用ture，等打包给后台的时候就改回false,
                    appId: data.appId, // 必填，公众号的唯一标识
                    timestamp: data.timeStamp, // 必填，生成签名的时间戳
                    nonceStr: data.nonceStr, // 必填，生成签名的随机串
                    signature: data.sign, // 必填，签名
                    jsApiList: ["chooseWXPay", "checkJsApi"], // 必填，需要使用的JS接口列表
                  });

                  wx.ready(() => {
                    wx.chooseWXPay({
                      timestamp: data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                      nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
                      package: data.packages, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                      signType: data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                      paySign: data.sign, // 支付签名
                      success: function (payRes) {
                        // 支付成功后的回调函数
                        Toast("支付成功");
                        vm.$router.push({
                          path: "/orderDetail",
                          query: { orderId: res.orderId },
                        });
                      },
                      cancel: function (payRes) {
                        // that.$message.error('取消支付')
                      },
                      fail: function (payRes) {
                        // that.$message.error('支付失败')
                      },
                    });
                  });
                });
            }
          });
      }
    },
    goRouter(data) {
      if (data.url) {
        this.$router.push(data.url);
      }
    },
  },
};
</script>
<style>
body {
  background: #f6f5fa;
}
</style>
<style lang="less" scoped="">
.home {
  margin: auto;
  background: #f6f5fa;

  .banner {
    img {
      width: 100%;
      display: block;
    }
  }

  .content {
    background: #f6f5fa;
    padding: 10px;
    padding-bottom: 80px;
  }

  .title {
    display: flex;
    align-items: center;

    .icon_fire {
      width: 20px;
    }

    .txt {
      margin-left: 10px;
      font-size: 14px;
    }
  }

  .list {
    overflow: hidden;
    margin-top: 10px;

    .item {
      width: 49%;
      margin-right: 2%;
      border-radius: 15px;
      background: #fff;
      overflow: hidden;
      float: left;
      margin-bottom: 10px;

      &:nth-child(2n) {
        margin-right: 0;
      }

      .item_content {
        padding: 10px;
      }

      .item_img {
        width: 100%;
        height: 173px;
        background-position: center center;
        background-size: cover;
        background-repeat: no-repeat;
      }

      .item_tt {
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        white-space: nowrap;
      }

      .item_price {
        margin-top: 8px;
        font-weight: 500;
        color: #f53939;
        font-size: 14px;

        .item_price_txt {
          margin-left: 5px;
          font-weight: 500;
        }
      }

      .item_footer {
        font-size: 12px;
        display: flex;
        margin-top: 5px;
        justify-content: space-between;
        align-items: center;

        .item_num {
          color: #9e9e9e;
          font-weight: 500;

          .item_num_txt {
            margin-left: 5px;
            font-weight: 800;
          }
        }

        .item_btn {
          color: #fff;
          border-color: #fa3534;
          background-color: #fa3534;
          width: auto;
          font-size: 12px;
          padding: 5px 5px;
          border-radius: 5px;
          text-align: center;
        }
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;

    .footerbox {
      display: flex;

      margin: auto;
      max-width: 500px;
    }

    .menu_item {
      color: #999faa;
      width: 50%;
      text-align: center;
      padding: 10px 0;

      .menu_icon {
        display: block;
        margin: auto;
        width: 20px;
      }

      .menu_name {
        font-size: 12px;
        margin-top: 5px;
      }

      &.active {
        color: #f53939;
      }
    }
  }
}
</style>
